package ntd.util.frame.action.database;

import cn.hutool.core.lang.Opt;
import cn.hutool.db.Entity;
import cn.hutool.db.sql.Order;
import cn.hutool.json.JSONUtil;
import com.c.opt.ComOpt;
import com.c.opt.query.ComOptQueryWrapper;
import com.c.opt.query.ComQueryInfo;
import com.ToolOpt;
import ntd.action.ActionAbs;
import ntd.action.bo.ActionInfo;
import ntd.action.bo.ActionOutBo;
import ntd.util.frame.action.database.enums.EnumDataLevel;
import ntd.util.frame.action.database.factory.FactoryTableBuild;

import java.util.List;

public class ActionTableList extends ActionAbs {

    @Override
    public ActionInfo info() {
        return new ActionInfo("数据-查询", "action-table-list", new ActionTableList());
    }

    @Override
    public ActionOutBo handle() {

        ComOpt<Object> comOpt = ToolOpt.get(actionInBo.getDataCode(), actionInBo.dsId());

        ComOptQueryWrapper queryWrapper = new ComOptQueryWrapper(actionInBo.getDataCode(), ComQueryInfo.transform(actionInBo.getParamStr("rules")));

        // 数据权限过滤
        Opt.ofBlankAble(actionInBo.getParamStr("dataLevel")).ifPresent(s -> queryWrapper.dataLevel(EnumDataLevel.valueOf(s)));

        // 私有筛选包装
        Opt.ofEmptyAble(FactoryTableBuild.build(actionInBo.getDataCode())).ifPresent(comQueryInfos -> comQueryInfos.forEach(queryWrapper::build));

        Opt.ofBlankAble(actionInBo.getParamStr("sorts")).ifPresent(str -> {
            if (JSONUtil.isTypeJSONArray(str)) {
                JSONUtil.toList(str, Order.class).forEach(queryWrapper::order);
            }
        });

        List<Entity> list = comOpt.list(queryWrapper);

        return new ActionOutBo(list);
    }

}
